// pages/referOrder/referOrder.js
let app = getApp();
const httpUtils = require('../../utils/httpUtils.js');
let tool = require('../../utils/tool.js');
let payStatusTimes = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageurl: 'https://material.sse100.cn/shop/',
    account: null,
    product: null,
    isCanChoose: false,
    id: null, ////商品id json [{"product\_id":1,"num":2},{"product\_id":2,"num":2}\]
    amount: null,
    hasfence: "",
    order_no: "",
    flag: true,
    coupon_id: "", //优惠券id
    score: "0", //积分
    address_id: "", //货物地址
    ptype: 0, //0  不显示地址  非0 显示地址
    address:"请选择收货地址",
    name:"",
    username:"",
    telNumber:"",
    

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(" options.userid:" + options.userid)
    var updata = new Array()
    // that.data.mData.forEach(function (item, index) {
    //   let itemData={
    //     id:item.id,
    //     select:item.select
    //   }
    //   updata.push(itemData)
    // })
    let itemData = {
      product_id: options.id,
      num: 1
    }
    updata.push(itemData)
    this.setData({
      id: updata,
    })
    this.placeorder();

   
  },
  placeorder: function () {
    let that = this
    wx.showLoading({
      title: '正在加载',
      mask: true
    })
    var info = JSON.stringify(this.data.id)
    console.log("info:" + info);
    httpUtils.placeorder({
      access_token: app.globalData.$TOKEN,
      from: 0,
      id: info

    }).then((res) => {
      wx.hideLoading()
      this.setData({
        ptype:res.data.ptype,
        product: res.data.product[0],
        amount: res.data.amount,
        hasfence: res.data.hasfence,
        courseGrade: res.data.grade,
        limit: res.data.limit
      })
    })
  },
  referCoder: function () {
    let that = this
    console.log("that.data.gradeId:" + that.data.gradeId)
    var addresss="";
    if ((that.data.address)!="请选择收货地址") {
      addresss=that.data.address;
    }
    if (that.data.ptype!=0&&addresss=="") {
      wx.showToast({
        title: '地址不能为空',
        icon: 'none',
        duration: 2000
      })
      return
      
    }
    wx.showLoading({
      title: '正在加载',
      mask: true
    })
    var info = JSON.stringify(this.data.id)
  
   
    httpUtils.placeorder({
      access_token: app.globalData.$TOKEN,
      openid: app.globalData.openid,
      from: 1,
      id: info,
      address: addresss,
      username: that.data.name,
      mobile: that.data.telNumber,
      coupon_id: that.data.coupon_id,
      score: that.data.score
    }).then((res) => {
      wx.hideLoading()
      //开始支付
      this.setData({
        order_no: res.data.order_no
      })

      wx.requestPayment({
        timeStamp: res.data.timeStamp,
        nonceStr: res.data.nonceStr,
        package: res.data.package,
        signType: res.data.signType,
        paySign: res.data.paySign,
        success: function (res) {
          //成功后调查询支付结果接口
          that.checkPayStatus();
        },
        fail: function (res) {
          // fail  
          if (res.errMsg == "requestPayment:fail cancel") {
            wx.showToast({
              title: '取消支付',
              icon: 'none',
              duration: 2000
            })
          } else {
            wx.showToast({
              title: '支付失败',
              icon: 'none',
              duration: 2000
            })
          }
        }
      })
    })
  },




  /**
   * 获取支付结果状态
   */
  checkPayStatus: function () {
    let that = this;
    wx.showLoading({
      title: '获取支付结果...',
      mask: true
    })
    let paramArr = {
      access_token: app.globalData.$TOKEN,
      order_no: that.data.order_no
    }
    let _id=that.data.id[0].product_id;
    let rs = tool.getSign(paramArr, app.globalData.key); //返回 bodyParam heaer sign
    let sign = rs.sign;
    let apiUrl = app.globalData.apiURL + "/api/Shop/orderinfo?sign=" + sign;
    let classPro = new Promise(
      function (resolve, reject) {
        wx.request({
          url: apiUrl,
          header: rs.header,
          data: rs.bodyParam,
          method: 'post',
          success(res) {
            resolve(res);
          }
        })
      }
    );

    classPro.then(function (res) {
      let that = this
      console.log(JSON.stringify(res))
      if (res.data.code === 1) {
        //支付成功
        wx.hideLoading();
        payStatusTimes = 0;
        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 2000
        })
        wx.redirectTo({
            url: '/pages/orderdetail/orderdetail?id='+_id+'&order_no='+paramArr.order_no,
        })
      } else if (1082 == res.data.code) {
        //支付未完成，5s,15s,30s后再轮询查下结果
        if (payStatusTimes == 3) {
          payStatusTimes = 0;
          wx.showToast({
            title: res.data.info,
            icon: 'none',
            duration: 3000
          });
          return;
        }
        let waitTime = payStatusTimes == 0 ? 5000 : payStatusTimes == 1 ? 15000 : 30000;
        payStatusTimes++;
        setTimeout(function () {
          that.checkPayStatus()
        }, waitTime)

      } else {
        //失败或者其他g
        wx.hideLoading();
        payStatusTimes = 0;
        wx.showToast({
          title: res.data.info,
          icon: 'none',
          duration: 3000
        });
      }

    })
  },
  chooseAddress: function () {
    let  that=this;
    wx.chooseAddress({
      success: (result) => {
        if (result) {
          that.setData({
            address:result.provinceName+""+result.cityName+""+result.countyName+""+ result.detailInfo,
            name:result.userName,
            telNumber:result.telNumber,
            username:result.userName+" "+result.telNumber
          })
  
        }
      },
    })
  },

  refer: function () {
    this.referCoder()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})